package com.tanhua.manage.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.UserFreeze;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.*;
import com.tanhua.manage.handler.PublishHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class UserService {

    @Autowired
    private List<PublishHandler> handlerList;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private PublishApi publishApi;

    @Reference
    private VideoApi videoApi;

    @Reference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference
    private UserFreezeApi userFreezeApi;

    /**
     * 接口名称：用户数据翻页
     */
    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        // 1.调用服务提供者api分页查询用户详情
        IPage<UserInfo> ipage = userInfoApi.findByPage(page, pagesize);

        PageResult pageResult = new PageResult(page, pagesize, (int) ipage.getTotal(), ipage.getRecords());

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：用户基本资料
     */
    public ResponseEntity<Object> findUserInfoById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 接口名称：动态分页
     */
    public ResponseEntity<Object> queryPublishList(Integer page, Integer pagesize, String uid, String state) {
        PageResult pageResult = null;
        if (uid != null) {
            //根据uid查询用户的动态
            pageResult = publishApi.findPublishList(page, pagesize, uid);
            EncapsulationPublish(pageResult);
        } else if (!StringUtils.isEmpty(state)) {
            //尝试使用策略模式
            //根据state查询动态
            for (PublishHandler handler : handlerList) {
                //判断由哪个处理器执行
                if (handler.shouldHandler(Integer.valueOf(state))) {
                    pageResult = handler.handle(page, pagesize, Integer.valueOf(state));
                    EncapsulationPublish(pageResult);
                }
            }
        } else {
            //查询所有动态
            pageResult = publishApi.queryAllPublishList(page, pagesize);
            EncapsulationPublish(pageResult);
        }
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 动态驳回
     * @param publishIdList
     * @return
     */
    public ResponseEntity<Object> PublishReject(List<String> publishIdList) {
        //遍历动态id
        for (String publishId : publishIdList) {
            //更新审核状态
            publishApi.updateState(publishId, 2);
        }
        //返回结果
        String message = "动态已驳回";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("message", message);
        return ResponseEntity.ok(resultMap);
    }

    /**
     * 动态通过
     * @param publishIdList
     * @return
     */
    public ResponseEntity<Object> PublishPass(List<String> publishIdList) {
        //遍历动态id
        for (String publishId : publishIdList) {
            //更新审核状态
            publishApi.updateState(publishId, 1);
        }
        //返回结果
        String message = "已通过审核";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("message", message);
        return ResponseEntity.ok(resultMap);
    }

    /**
     * 接口名称：视频记录翻页
     */
    public ResponseEntity<Object> queryVideoList(Integer page, Integer pagesize, Long uid) {
        // 1.调用服务提供者api分页查询小视频列表
        PageResult pageResult = videoApi.queryVideoListById(page, pagesize, uid);

        // 获取当前页的数据
        List<Video> videoList = (List<Video>) pageResult.getItems();

        // 2.封装返回结果
        List<VideoVo> voList = new ArrayList<>();
        if (videoList != null) {
            for (Video video : videoList) {
                // 2.1 创建vo
                VideoVo vo = new VideoVo();

                // 2.2 封装数据
                BeanUtils.copyProperties(video, vo);

                // 查询用户详情
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }

                vo.setId(video.getId().toString());
                vo.setCover(video.getPicUrl());
                vo.setSignature(video.getText());
                vo.setHasLiked(0);

                // 2.3 添加vo到集合
                voList.add(vo);
            }
        }
        // 3.重新设置items的值
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 查询动态详情
     *
     * @param id
     * @return
     */
    public ResponseEntity<Object> findById(String id) {
        // 1.调用服务提供者api查询动态详情
        Publish publish = publishApi.findById(id);

        // 2.封装返回结果
        MovementsVo vo = new MovementsVo();

        // 2.1 封装数据：动态信息
        BeanUtils.copyProperties(publish, vo);
        // 封装图片url
        if (publish.getMedias() != null) {
            String[] imageContent = publish.getMedias().toArray(new String[]{});
            vo.setImageContent(imageContent);
        }

        // 2.2 封装数据：用户详情
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            // 转换标签
            if (!StringUtils.isEmpty(userInfo.getTags())) {
                String[] tags = userInfo.getTags().split(",");
                vo.setTags(tags);
            }
        }

        // 2.3 封装其他属性
        vo.setId(publish.getId().toString());
        vo.setDistance("50米");
        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));

        return ResponseEntity.ok(vo);
    }

    /**
     * 查询动态的评论列表
     *
     * @param page
     * @param pagesize
     * @param messageID
     * @return
     */
    public ResponseEntity<Object> queryCommentList(Integer page, Integer pagesize, String messageID) {
        // 1.调用服务提供者api分页查询评论列表
        PageResult pageResult = commentApi.queryCommentsList(page, pagesize, messageID);

        // 获取当前页数据
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        // 2.封装返回结果
        List<CommentVo> voList = new ArrayList<>();

        if (commentList != null) {
            for (Comment comment : commentList) {
                // 2.1 创建vo
                CommentVo vo = new CommentVo();

                // 2.2 封装数据
                // 封装评论数据
                vo.setId(comment.getId().toString());
                vo.setContent(comment.getContent());
                vo.setCreateDate(new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(new Date(comment.getCreated())));
                vo.setLikeCount(comment.getLikeCount());
                vo.setHasLiked(0);

                // 封装用户详情
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                if (userInfo != null) {
                    vo.setAvatar(userInfo.getAvatar());
                    vo.setNickname(userInfo.getNickname());
                }

                // 2.3 添加vo到集合
                voList.add(vo);
            }
        }

        // 3.重新设置items的值
        pageResult.setItems(voList);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 抽离封装动态的方法
     */
    public void EncapsulationPublish(PageResult pageResult) {
        List<Publish> publishList = (List<Publish>) pageResult.getItems();
        // 1.创建封装返回的结果MovementsVo集合
        List<MovementsVo> voList = new ArrayList<>();
        if (publishList != null) {
            //2.遍历查询动态集合
            for (Publish publish : publishList) {
                // 3.1 创建vo对象
                MovementsVo vo = new MovementsVo();
                // 3.2 封装动态的数据
                BeanUtils.copyProperties(publish, vo);
                // 3.3 封装数据：先查询用户详情，再封装
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if (userInfo != null) {
                    //movementsVo.setUserId(0L);
                    //movementsVo.setAvatar("");
                    //movementsVo.setNickname("");
                    //movementsVo.setGender("");
                    //movementsVo.setAge(0);
                    BeanUtils.copyProperties(userInfo, vo);

                    if (userInfo.getTags() != null) {
                        // 3.4movementsVo.setTags(new String[] ()); 切割数组
                        vo.setTags(userInfo.getTags().split(","));
                    }
                    // 3.5 处理动态中未能拷贝的字段
                    vo.setId(publish.getId().toString());
                    if (publish.getMedias() != null) {
                        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                    }
                    vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(publish.getCreated())));
                }
                // 3.6 对象添加到集合
                voList.add(vo);
            }
        }
        // 4.在把封装好的vo集合设置到分页对象中
        pageResult.setItems(voList);
    }

    /**
     * 用户冻结操作
     *
     * @param param
     * @return
     */
    public ResponseEntity<Object> userFreeze(Map<String, Object> param) {
        //1.获取接收的参数
        Integer userId = Integer.valueOf(param.get("userId").toString());
        Integer freezingTime = Integer.valueOf(param.get("freezingTime").toString());
        Integer freezingRange = Integer.valueOf(param.get("freezingRange").toString());
        String reasonsForFreezing = param.get("reasonsForFreezing").toString();
        String frozenRemarks = param.get("frozenRemarks").toString();

        //2.判断用户冻结数据库是否有数据
        UserFreeze userFreeze = userFreezeApi.queryFreezeDetailById(userId);
        if (userFreeze == null) {
            //3.创建userFreeze保存数据
            userFreeze = new UserFreeze();
            userFreeze.setUserId(userId);
            userFreeze.setFreezingTime(freezingTime);
            userFreeze.setFreezingRange(freezingRange);
            userFreeze.setReasonsForFreezing(reasonsForFreezing);
            userFreeze.setFrozenRemarks(frozenRemarks);
            userFreezeApi.insertUserFreezeDetails(userFreeze);
            if (freezingTime == 1) {
                redisTemplate.opsForValue().set("userFreezeId_" + userFreeze.getUserId(),
                        userFreeze.getUserId() + "", Duration.ofDays(3));
            } else if (freezingTime == 2) {
                redisTemplate.opsForValue().set("userFreezeId_" + userFreeze.getUserId(),
                        userFreeze.getUserId() + "", Duration.ofDays(7));
            } else {
                redisTemplate.opsForValue().set("userFreezeId_" + userFreeze.getUserId(),
                        userFreeze.getUserId() + "");
            }
        } else {
            userFreeze.setFreezingTime(freezingTime);
            userFreeze.setFreezingRange(freezingRange);
            userFreeze.setReasonsForFreezing(reasonsForFreezing);
            userFreeze.setFrozenRemarks(frozenRemarks);
            userFreezeApi.update(userFreeze);
            if (freezingTime == 1) {
                redisTemplate.opsForValue().set("userFreezeId_" + userFreeze.getUserId() + "_time",
                        userFreeze.getUserId() + "", Duration.ofDays(3));
            } else if (freezingTime == 2) {
                redisTemplate.opsForValue().set("userFreezeId_" + userFreeze.getUserId() + "_time",
                        userFreeze.getUserId() + "", Duration.ofDays(7));
            } else {
                redisTemplate.opsForValue().set("userFreezeId_" + userFreeze.getUserId() + "_time",
                        userFreeze.getUserId() + "");
            }
        }



        //3.调用服务提供者api查询用户详情
        UserInfo userInfo = userInfoApi.findById(userId.longValue());

        //状态字段  userStatus （1：正常，2：冻结状态）
        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);



        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");

        return ResponseEntity.ok(map);
    }

    /**
     * 用户解冻操作
     *
     * @param param
     * @return
     */
    public ResponseEntity<Object> unFreeze(Map<String, Object> param) {
        //1.获取前端传来的参数数据
        Integer userId = Integer.valueOf(param.get("userId").toString());
        String frozenRemarks = param.get("frozenRemarks").toString();

        //2.调用服务者api，将解冻原因保存到数据库
        UserFreeze userFreeze = userFreezeApi.queryFreezeDetailById(userId);
        if (userFreeze != null) {
            userFreeze.setReasonsForThawing(frozenRemarks);
            userFreeze.setFreezingRange(0);
            userFreeze.setFreezingTime(0);
            userFreezeApi.update(userFreeze);
        }



        UserInfo userInfo = userInfoApi.findById(userId.longValue());
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);

        Map<String, String> result = new HashMap<>();
        result.put("message", "操作成功");

        return ResponseEntity.ok(result);
    }
}
